<script setup lang="ts">
import {
  NUpload,
  NUploadDragger,
  type UploadCustomRequestOptions,
  NIcon,
  uploadProps
} from 'naive-ui'
import { CloudUploadRound } from '@vicons/material'
import { sendRequest } from '@/utils/api'
import type { AxiosProgressEvent } from 'axios'

defineProps(uploadProps)

const customRequest = ({ file, onFinish, onError, onProgress }: UploadCustomRequestOptions) => {
  const formData = new FormData()
  formData.append('file', file.file as File)

  sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent: AxiosProgressEvent) => {
        onProgress({
          percent: progressEvent.progress || 0
        })
      }
    }
  })
    .then(([error, res]) => {
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      // @ts-ignore
      file.file.remoteId = res.data.fileId
      file.url = res.data.url
      onFinish()
    })
    .catch(() => {
      onError()
    })
}
</script>

<template>
  <NUpload
    v-bind="$props"
    multiple
    list-type="image-card"
    :custom-request="customRequest"
  >
    <NUploadDragger>
      <div style="display: flex; flex-direction: column; align-items: center; padding: 3px 5px">
        <NIcon
          color="#ccc"
          size="32"
        >
          <CloudUploadRound />
        </NIcon>
        <span style="color: #666; font-size: 12px">点击或拖拽文件到此处上传</span>
      </div>
    </NUploadDragger>
  </NUpload>
</template>
